package com.dream.libxrec.utils;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 帧率计算工具类
 */
public class CallRateCounter {

    private final AtomicLong callCount = new AtomicLong(0);
    private long startTime;
    private boolean started = false;

    public CallRateCounter() {}

    public void incrementCallCount() {
        if (!started) {
            startTime = System.currentTimeMillis();
            started = true;
            startTimer();
        }
        callCount.incrementAndGet();
    }

    private void startTimer(){
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                printAverageCallsPerSecond();
            }
        }, 5000, 5000);
        //每5秒打印一次帧率
    }

    private void printAverageCallsPerSecond() {
        if (!started) {
            return;
        }
        long currentTime = System.currentTimeMillis();
        long elapsedTime = currentTime - startTime;
        if (elapsedTime == 0) {
            System.out.println("Average calls per second: 0");
        } else {
            double rate = callCount.get() / (elapsedTime / 1000.0);
            System.out.println("Average calls per second: " + rate);
        }
    }
}